package com.qiku.job;

import com.qiku.entity.Article;
import com.qiku.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 每个?分钟把redis中的浏览量更新到数据库
 */
@Component
public class UpdateViewCountJob {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ArticleService articleService;
    @Scheduled(cron = "0/25 * * * * ?")
    public void updateViewCount(){
        //获取redis中的浏览量
        Map<Long,Long> viewCountMap = redisTemplate.opsForHash().entries("articleViewCount");
        Article article = new Article();
        List<Article> articleList = new ArrayList<>();
        //遍历viewCountMap
        Set<Map.Entry<Long, Long>> entries = viewCountMap.entrySet();
        Iterator<Map.Entry<Long, Long>> iterator = entries.iterator();
        while (iterator.hasNext()){
            Map.Entry<Long, Long> next = iterator.next();
            Long key = next.getKey();
            Long value = next.getValue();
            article.setId(key);
            article.setViewCount(value);
            articleList.add(article);
        }
        //更新到数据库中
        articleService.updateBatchById(articleList);
    }
}
